package com.jie.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jie.eduservice.entity.EduSubject;
import com.jie.eduservice.entity.excel.SubjectData;
import com.jie.eduservice.service.EduSubjectService;
import com.jie.servicebase.exception.GuLiException;

import java.util.Map;

/**
 * SubjectExcelListener不能交给spring进行管理, 需要自己new, 不能直接注入其它对象
 * 感觉效率有些低, 做了好多数据库查询, 虽然课程分类不会太多
 * @author XieZhiJie
 * @create 2020-10-08 15:06
 */
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    private final EduSubjectService subjectService;

    public SubjectExcelListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }

    // 一行一行读取excel内容(第一行是表头, 不读取)
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null) {
            throw new GuLiException(20001, "文件数据为空");
        }

        // 判断一级分类是否重复
        EduSubject oneSubject = this.getOneSubject(subjectData.getOneSubjectName());
        if (oneSubject == null) {  // 若为空则进行添加
            oneSubject = new EduSubject();
            oneSubject.setParentId("0");
            oneSubject.setTitle(subjectData.getOneSubjectName());  // 二级分类名称
            subjectService.save(oneSubject);
        }

        // 判断二级分类是否重复(若是有三级分类或者更多的时候则需要重写这里了, 暂时先不用写更多的分类)
        String pid = oneSubject.getId();  // 获取一级分类的id值
        EduSubject twoSubject = this.getTwoSubject(subjectData.getOneSubjectName(), pid);
        if (twoSubject == null) {  // 若为空则进行添加
            twoSubject = new EduSubject();
            twoSubject.setParentId(pid);
            twoSubject.setTitle(subjectData.getTwoSubjectName());  // 二级分类名称
            subjectService.save(twoSubject);
        }
    }

    // 读取表头内容
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {

    }

    // 读取完成后
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    // 获取一级分类的信息
    private EduSubject getOneSubject(String subjectName) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", subjectName);
        wrapper.eq("parent_id", "0");
        return subjectService.getOne(wrapper);
    }

    // 获取二级分类的信息()
    private EduSubject getTwoSubject(String subjectName, String pid) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", subjectName);
        wrapper.eq("parent_id", pid);
        return subjectService.getOne(wrapper);
    }

}
